package cn.hl.hm.controller.manage;

import cn.hl.hm.controller.driver.DriverInfoController;
import cn.hl.hm.dao.TBackstageUserEntityMapper;
import cn.hl.hm.entity.Driver;
import cn.hl.hm.entity.DriverStatusHistory;
import cn.hl.hm.entity.SecurityFeeTypeHistory;
import cn.hl.hm.entity.backstage.TBackstageUserEntity;
import cn.hl.hm.logic.manage.DriverManageLogic;
import cn.hl.hm.service.DriverStatusHistoryService;
import cn.hl.hm.service.SecurityFeeTypeHistoryService;
import cn.hl.hm.util.ExportData;
import cn.hl.hm.util.InfoCode;
import cn.hl.hm.util.List2Map;
import cn.hl.hm.vo.DriverDetailVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * 管理系统：司机管理
 * Created by tarzan on 2017/10/31.
 */
@Controller
@RequestMapping(value = "/manage/driver")
public class DriverManageController {
    private static final Logger logger = LoggerFactory.getLogger(DriverInfoController.class);
    @Autowired
    DriverManageLogic driverManageLogic;
    @Autowired
    DriverStatusHistoryService driverStatusHistoryService;
    @Autowired
    SecurityFeeTypeHistoryService securityFeeTypeHistoryService;
    @Autowired
    TBackstageUserEntityMapper backstageUserEntityMapper;

    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public String driverList(@CookieValue(required = false, value = "manageToken") String manageToken,
                             @RequestParam(required = false) String name,
                             @RequestParam(required = false) String driverPhone,
                             @RequestParam(required = false) String driverStatus,
                             @RequestParam(required = false) String plateNumber,
                             @RequestParam(required = false, defaultValue = "1") Integer pageId,
                             @RequestParam(required = false, defaultValue = "10") Integer pageCount,
                             HttpServletRequest request, ModelMap modelMap) throws IOException {
        logger.info("司机---列表---/manage/driver/list");
        try {
            modelMap.addAttribute("infoCode", InfoCode.SUCCESS);
            driverManageLogic.getDriverList(name, driverPhone, driverStatus,plateNumber, pageId, pageCount, modelMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "manage/driver/driver.list";
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addDriver(@CookieValue(required = false, value = "manageToken") String manageToken,
                            @RequestParam(required = false) String name,
                            @RequestParam(required = false) String headPic,
                            @RequestParam(required = false) String sex,
                            @RequestParam(required = false) String driverPhone,
                            @RequestParam(required = false) String idCard,
                            @RequestParam(required = false) String idCardFrontPic,
                            @RequestParam(required = false) String idCardBackPic,
                            @RequestParam(required = false) String driverLicense,
                            @RequestParam(required = false) String driverLicensePic,
                            @RequestParam(required = false) String qualificationCertificatePic,
                            HttpServletRequest request, ModelMap modelMap) throws IOException {
        logger.info("司机---添加---/manage/driver/add");
        try {
            Driver driver=new Driver();
            driver.setName(name);
            driver.setHeadPic(headPic);
            driver.setSex(sex);
            driver.setDriverPhone(driverPhone);
            driver.setIdCard(idCard);
            driver.setIdCardFrontPic(idCardFrontPic);
            driver.setIdCardBackPic(idCardBackPic);
            driver.setDriverLicense(driverLicense);
            driver.setDriverLicensePic(driverLicensePic);
            driver.setQualificationCertificatePic(qualificationCertificatePic);
            driverManageLogic.addDriver(driver,"4003",modelMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "manage/driver/driver.result";
    }

//    @RequestMapping(value = "/delete", method = RequestMethod.POST)
//    public String deleteDriver(@CookieValue(required = false, value = "manageToken") String manageToken,
//                               @RequestParam(required = false) Integer driverId,
//                               HttpServletRequest request, ModelMap modelMap) throws IOException {
//        logger.info("司机---列表---/manage/driver/delete");
//        try {
//            driverManageLogic.deleteDriver(driverId, modelMap);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return "manage/driver/driver.result";
//    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String updateDriver(@CookieValue(required = false, value = "manageToken") String manageToken,
                               @RequestParam(required = false) Integer driverId,
                               @RequestParam(required = false) String driverStatus,
                               @RequestParam(required = false) String name,
                               @RequestParam(required = false) String headPic,
                               @RequestParam(required = false) String sex,
                               @RequestParam(required = false) String driverPhone,
                               @RequestParam(required = false) String idCard,
                               @RequestParam(required = false) String idCardFrontPic,
                               @RequestParam(required = false) String idCardBackPic,
                               @RequestParam(required = false) String driverLicense,
                               @RequestParam(required = false) String driverLicensePic,
                               @RequestParam(required = false) String qualificationCertificatePic,
                               @RequestParam(required = false) String updateBy,
                               HttpServletRequest request, ModelMap modelMap) throws IOException {
        logger.info("司机---修改---/manage/driver/update");
        try {
            Driver driver=new Driver();
            driver.setId(driverId);
            driver.setDriverStatus(driverStatus);
            driver.setName(name);
            driver.setHeadPic(headPic);
            driver.setSex(sex);
            driver.setDriverPhone(driverPhone);
            driver.setIdCard(idCard);
            driver.setIdCardFrontPic(idCardFrontPic);
            driver.setIdCardBackPic(idCardBackPic);
            driver.setDriverLicense(driverLicense);
            driver.setDriverLicensePic(driverLicensePic);
            driver.setQualificationCertificatePic(qualificationCertificatePic);
            driverStatusHistoryService.save(driverId, updateBy, driverStatus);
            driverManageLogic.updateDriver(driver, modelMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "manage/driver/driver.result";
    }

    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public String driverDetail(@CookieValue(required = false, value = "manageToken") String manageToken,
                               @RequestParam(required = false) Integer driverId,
                               @RequestParam(required = false) String driverPhone,
                               HttpServletRequest request, ModelMap modelMap) throws IOException {
        logger.info("司机---详情---/manage/driver/detail");
        try {
            driverManageLogic.getDriverDetail(driverId,driverPhone, modelMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "manage/driver/driver.detail";
    }

    @RequestMapping(value = "/check", method = RequestMethod.POST)
    public String checkDriver(@CookieValue(required = false, value = "manageToken") String manageToken,
                               @RequestParam(required = true) Integer driverId,
                               @RequestParam(required = true) String checkState,
                               @RequestParam(required = false) String driverUnpassReason,
                              @RequestParam(required = true) String updateBy,
                               HttpServletRequest request, ModelMap modelMap) throws IOException {
        logger.info("司机---审核---/manage/driver/check");
        try {
            driverStatusHistoryService.save(driverId, updateBy, checkState);
            driverManageLogic.checkDriver(driverId, checkState,driverUnpassReason, modelMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "manage/driver/driver.result";
    }

    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public void export(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws IOException {
        logger.info("司机---列表导出---/manage/driver/export");
        try {
            String ctxPath = request.getSession().getServletContext().getRealPath("/") + "export/";
            String fileName = "";
            File file = new File(ctxPath.toString());

            if (!file.exists()) {
                file.mkdir();
                try {
                    Thread.sleep(1500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            List<DriverDetailVo> list=driverManageLogic.getDriverAll();
            fileName=System.currentTimeMillis()+".xls";
            ExportData.exportDriverListExcel(ctxPath + fileName, list);

            FileInputStream input=new FileInputStream(ctxPath + fileName);
            OutputStream output=response.getOutputStream();
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
            byte[] b=new byte[1024*1024];
            int len=0;
            while((len=input.read(b))!=-1){
                output.write(b,0,len);
            }
            input.close();
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  ;
    }

    @RequestMapping(value = "/checkerList", method = RequestMethod.GET)
    public String checkDriver(@RequestParam Integer type,
            HttpServletRequest request, ModelMap modelMap) throws IOException {
        logger.info("司机---审核人员列表---/manage/driver/checkerList");
        try {
            List<Integer> updateBys=null;
            if (type.equals(1)) {
                updateBys=driverStatusHistoryService.selectUpdateBys();
            }else if(type.equals(2)){
                updateBys=securityFeeTypeHistoryService.selectUpdateBys();
            }
            if (updateBys!=null&&updateBys.size()>0) {
                List<TBackstageUserEntity> tBackstageUserEntities = backstageUserEntityMapper.selectListByIds(updateBys);
                modelMap.addAttribute("userList",tBackstageUserEntities);
            }
            modelMap.addAttribute("infoCode", InfoCode.SUCCESS);
        } catch (Exception e) {
            modelMap.addAttribute("infoCode", InfoCode.FAILURE);
            e.printStackTrace();
        }
        return "manage/driver/driver.checkerList";
    }

    @RequestMapping(value = "/statusHistoryList", method = RequestMethod.GET)
    public String statusHistoryList(@RequestParam(required = false) String date,
                                    @RequestParam(required = false) Integer updateBy,
                                    @RequestParam(required = true)  Integer driverId,
            HttpServletRequest request, ModelMap modelMap) throws IOException {
        logger.info("司机---审核---/manage/driver/statusHistoryList");
        try {
            String endTime=null;
            if(date!=null && date.length()>0){
                endTime=date+" 23:59:59";
            }
            List<DriverStatusHistory> driverStatusHistoryList = driverStatusHistoryService.
                    selectListByPrimaryKeySelective(driverId, date, endTime, updateBy);
            List2Map listUtil = List2Map.getInstance();
            if (listUtil.isNotEmpty(driverStatusHistoryList)) {
                List<Integer> ids=listUtil.getFieldList("getUpdateBy",driverStatusHistoryList);
                if (listUtil.isNotEmpty(ids)) {
                    Map<Integer,TBackstageUserEntity> userMap = listUtil.tobeMap("getId", backstageUserEntityMapper.selectListByIds(ids));
                    TBackstageUserEntity tBackstageUserEntity=null;
                    for (DriverStatusHistory driverStatusHistory : driverStatusHistoryList) {
                        tBackstageUserEntity=userMap.get(driverStatusHistory.getUpdateBy());
                        if (tBackstageUserEntity!=null) {
                            driverStatusHistory.setUpdaterMailBox(tBackstageUserEntity.getMailbox());
                        }
                    }
                    modelMap.addAttribute("driverStatusHistoryList",driverStatusHistoryList);
                }
            }
            modelMap.addAttribute("infoCode", InfoCode.SUCCESS);
        } catch (Exception e) {
            modelMap.addAttribute("infoCode", InfoCode.FAILURE);
            e.printStackTrace();
        }
        return "manage/driver/driver.statusHistoryList";
    }

    @RequestMapping(value = "/securityFeeTypeHistoryList", method = RequestMethod.GET)
    public String securityFeeTypeHistoryList(@RequestParam(required = false) String date,
                                    @RequestParam(required = false) Integer updateBy,
                                    @RequestParam(required = true)  Integer driverId,
            HttpServletRequest request, ModelMap modelMap) throws IOException {
        logger.info("司机---审核---/manage/driver/securityFeeTypeHistoryList");
        try {
            String endTime=null;
            if(date!=null && date.length()>0){
                endTime=date+" 23:59:59";
            }
            List<SecurityFeeTypeHistory> securityFeeTypeHistoryList = securityFeeTypeHistoryService.
                    selectListByPrimaryKeySelective(driverId, date, endTime, updateBy);
            List2Map listUtil = List2Map.getInstance();
            if (listUtil.isNotEmpty(securityFeeTypeHistoryList)) {
                List<Integer> ids=listUtil.getFieldList("getUpdateBy",securityFeeTypeHistoryList);
                if (listUtil.isNotEmpty(ids)) {
                    Map<Integer,TBackstageUserEntity> userMap = listUtil.tobeMap("getId", backstageUserEntityMapper.selectListByIds(ids));
                    TBackstageUserEntity tBackstageUserEntity=null;
                    for (SecurityFeeTypeHistory feeTypeHistory : securityFeeTypeHistoryList) {
                        tBackstageUserEntity=userMap.get(feeTypeHistory.getUpdateBy());
                        if (tBackstageUserEntity!=null) {
                            feeTypeHistory.setUpdaterMailBox(tBackstageUserEntity.getMailbox());
                        }
                    }
                    modelMap.addAttribute("securityFeeTypeHistoryList",securityFeeTypeHistoryList);

                }
            }
            modelMap.addAttribute("infoCode", InfoCode.SUCCESS);
        } catch (Exception e) {
            modelMap.addAttribute("infoCode", InfoCode.FAILURE);
            e.printStackTrace();
        }
        return "manage/driver/driver.securityFeeTypeHistoryList";
    }


}
